package cn.xzc.job.pojo;

import cn.xzc.job.ErrorHandler;

import java.lang.reflect.UndeclaredThrowableException;
import java.util.Objects;

/**
 * runnable并运行过程中抛出的异常处理
 *
 * @author xzc
 * 当前时间 2024-02-12 21:30:00
 */
public class DelegatingErrorHandlingRunnable implements Runnable {

    private final Runnable delegate;

    private final ErrorHandler errorHandler;


    /**
     * Create a new DelegatingErrorHandlingRunnable.
     *
     * @param delegate     the Runnable implementation to delegate to
     * @param errorHandler the ErrorHandler for handling any exceptions
     */
    public DelegatingErrorHandlingRunnable(Runnable delegate, ErrorHandler errorHandler) {
        this.delegate = delegate;
        this.errorHandler = errorHandler;
    }

    @Override
    public void run() {
        try {
            this.delegate.run();
        } catch (UndeclaredThrowableException ex) {
            //获取未声明的异常然后处理
            this.errorHandler.handleError(ex.getUndeclaredThrowable());
        } catch (Throwable ex) {
            this.errorHandler.handleError(ex);
        }
    }

    @Override
    public String toString() {
        return "DelegatingErrorHandlingRunnable for " + this.delegate;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof DelegatingErrorHandlingRunnable)) {
            return false;
        }
        DelegatingErrorHandlingRunnable that = (DelegatingErrorHandlingRunnable) o;
        return Objects.equals(delegate, that.delegate) && Objects.equals(errorHandler, that.errorHandler);
    }

    @Override
    public int hashCode() {
        return Objects.hash(delegate, errorHandler);
    }
}